﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TemplateWeb.Models;
using TemplateWeb.Helpers;
using TemplateWeb.ShoppingCartModule;
using TemplateWeb.Models.ViewModels;
using System.Web.Security;

namespace TemplateWeb.Controllers
{
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            return View(CreateViewModel(data));
        }

        public ActionResult TinTuc(int idloaitintuc = -1)
        {
            if (idloaitintuc == -1)
            {
                idloaitintuc = _repLoaiTinTuc.SelectAll().First().ID;
            }
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_TINTUC,
                IDLoaiTinTuc = idloaitintuc
            };
            return View(CreateViewModel(data));
        }

        public ActionResult ChiTietTinTuc(int id)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CHITIETTINTUC,
                IntID = id
            };
            return View(CreateViewModel(data));
        }

        public ActionResult GioiThieu()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            return View(CreateViewModel(data));
        }

        public ActionResult DoiTac()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_DOITAC
            };
            return View(CreateViewModel(data));
        }

        public ActionResult ChiTietDoiTac(int id)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CHITIETDOITAC,
                IntID = id
            };
            return View(CreateViewModel(data));
        }

        public ActionResult LienHe()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            return View(CreateViewModel(data));
        }

        public ActionResult YeuCauTimSach()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            return View(CreateViewModel(data));
        }

        public ActionResult Sach(int idloaisach = -1)
        {
            if (idloaisach == -1)
            {
                idloaisach = _repLoaiSach.SelectAll().First().ID;
            }
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_SACH,
                IDLoaiSach = idloaisach
            };
            return View(CreateViewModel(data));
        }

        public ActionResult DoLuuNiem()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_DOLUUNIEM,
            };
            return View(CreateViewModel(data));
        }

        public ActionResult ChiTietSach(int id)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CHITIETSACH,
                IntID = id
            };
            return View(CreateViewModel(data));
        }

        public ActionResult ChiTietDoLuuNiem(int id)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CHITIETDOLUUNIEM,
                IntID = id
            };
            return View(CreateViewModel(data));
        }

        public ActionResult ChiTietGocChiaSe(int id)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CHITIETGOCCHIASE,
                IntID = id
            };
            return View(CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult InsertHopThu(FormCollection forms)
        {
            string hoten = forms.GetValues("HopThu_HoTen")[0];
            string email = forms.GetValues("HopThu_Email")[0];
            string tieude = forms.GetValues("HopThu_TieuDe")[0];
            string noidung = forms.GetValues("HopThu_NoiDung")[0];

            var newItem = new HopThu
            {
                EmailNguoiHoi = email,
                TieuDe = tieude,
                NoiDung = noidung,
                NgayHoi = DateTime.Now,
                DaPhanHoi = false,
                HoTen = hoten
            };
            var result = _repHopThu.Insert(newItem);
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            ViewData["HoiDap"] = result ? "Thư của bạn đã được gửi đi, sau khi xem xét chúng tôi sẽ gửi phản hồi cho bạn!" : "Thư của bạn chưa được gửi đi, có lỗi sảy ra trong quá trình gửi câu hỏi.";
            return View("YeuCauTimSach", CreateViewModel(data));
        }

        public ActionResult Login()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_REGISTER
            };
            return View(CreateViewModel(data));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ThemBaiChiaSe()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_THEMCHIASE
            };
            ViewData["ThemBaiChiaSe"] = null;
            return View(CreateViewModel(data));
        }

        ////////////////////// SHOPPING CART ////////////////////////
        public ActionResult AddToCart(int id, int idloaisach, int num = 0)
        {
            // Retrieve the food from the database 
            var addedItem = _repSanPham.SelectByID(id);

            // Add it to the shopping cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);
            if (num == 0)
            {
                cart.AddToCart(addedItem);
            }
            else
            {
                cart.AddToCart(addedItem, num);
            }

            // Go back to the main store page for more shopping 
            // Set up our ViewModel 
            return RedirectToAction("Sach", new { idloaisach = idloaisach });
        }

        public ActionResult AddToCart2(int id, int num = 0)
        {
            // Retrieve the food from the database 
            var addedItem = _repSanPham.SelectByID(id);

            // Add it to the shopping cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);
            if (num == 0)
            {
                cart.AddToCart(addedItem);
            }
            else
            {
                cart.AddToCart(addedItem, num);
            }

            // Go back to the main store page for more shopping 
            // Set up our ViewModel 
            return RedirectToAction("DoLuuNiem");
        }


        public ActionResult UpdateQuantityToCart(int id, int num = 0)
        {
            // Retrieve the food from the database 
            var addedItem = _repSanPham.SelectByID(id);

            // Add it to the shopping cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);
            if (num == 0)
            {
                cart.AddToCart(addedItem);
            }
            else
            {
                cart.AddToCart(addedItem, num);
            }

            // Go back to the main store page for more shopping 
            // Set up our ViewModel 
            return RedirectToAction("XemGioHang");
        }

        public ActionResult RemoveFromCart(int id)
        {
            // Remove the item from the cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);

            // Get the name of the food to display confirmation 
            string foodName = _repSanPham.SelectByID(_repCart.SelectByRecordID(id).IDSanPham.Value).TenSanPham;

            // Remove from cart 
            cart.RemoveFromCart(id);

            // Go back to the main store page for more shopping 
            // Set up our ViewModel 
            return RedirectToAction("XemGioHang");
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Approve(FormCollection forms)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ORDER
            };

            var groupViewModel = CreateViewModel(data);
            string username = string.Empty;

            // Redirect to 
            if (!User.Identity.IsAuthenticated)
            {
                return View("Login", groupViewModel);
            }

            return View("ApproveOrder", groupViewModel);
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddOrder(FormCollection forms)
        {
            string chuthich = forms.GetValues("Order_ChuThich")[0];
            string diachinguoinhan = forms.GetValues("Order_DiaChiNguoiNhan")[0];
            string phonenguoinhan = forms.GetValues("Order_SoDienThoaiNguoiNhan")[0];
            string tennguoinhan = forms.GetValues("Order_TenNguoiNhan")[0];
            // First insert new order
            var newOrder = new DonDatHang
            {
                IDUser = Guid.Parse(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString()),
                NgayDatHang = DateTime.Now,
                DaXacNhan = false,
                DaGiaoHang = false,
                ChuThich = chuthich,
                DiaChiNguoiNhan = diachinguoinhan,
                SoDienThoaiNguoiNhan = phonenguoinhan,
                TenNguoiNhan = tennguoinhan
            };

            var result = _repDonDatHang.Insert(newOrder);

            if (result)
            {
                // Next insert order details
                var cart = ShoppingCart.GetCart(this.HttpContext);
                foreach (var item in cart.GetCartItems())
                {
                    var itemBuy = _repSanPham.SelectByID(item.IDSanPham.Value);
                    var orderDetail = new ChiTietDonDatHang
                    {
                        IDDonDatHang = newOrder.ID,
                        IDSanPham = itemBuy.ID,
                        SoLuong = item.SoLuong,
                        Gia = itemBuy.GiaBan
                    };
                    result = _repChiTietDonDatHang.Insert(orderDetail);
                }
                cart.EmptyCart();
            }
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ORDERHISTORY,
                GuidID = newOrder.IDUser.Value
            };
            ViewData["OrderResult"] = "Đặt hàng thành công! chúng tôi sẽ xử lý đơn hàng trong thời gian sớm nhất có thể";
            return View("OrdersHistory", CreateViewModel(data));
        }

        public ActionResult XemGioHang()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX,
            };
            return View(CreateViewModel(data));
        }

        public ActionResult OrdersHistory(string username)
        {
            var iduser = _repNguoiDung.SelectByUserName(username).BaseInfo.ID;
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ORDERHISTORY,
                GuidID = iduser
            };
            return View(CreateViewModel(data));
        }

        public ActionResult SelectOrderDetailByIDOrder(Guid iduser, int idorder)
        {
            var data = new DataTransferViewModel
            {
                GuidID = iduser,
                IDDonDatHang = idorder,
                EnumViewModelType = EnumViewModel.HOME_ORDERHISTORY_ORDERDETAIL,
            };
            return View("OrdersHistory", CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult TimKiem(FormCollection forms)
        {
            var loaisanpham = forms.GetValues("LoaiSanPham")[0];
            var tukhoa = forms.GetValues("TuKhoa")[0];
            var tacgia = forms.GetValues("TimKiemTacGia")[0];

            ViewData["TuKhoa"] = tukhoa;
            ViewData["TacGia"] = tacgia;

            var data = new DataTransferViewModel
            {
                TimKiem_LoaiSanPham = loaisanpham,
                TimKiem_TuKhoa = tukhoa,
                TimKiem_TacGia = tacgia,
                EnumViewModelType = EnumViewModel.HOME_TIMKIEM,
            };
            return View("KetQuaTimKiem", CreateViewModel(data));
        }
    }
}

